/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.peng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.peng.domain.Comment;
import me.peng.domain.RecyclerAddress;
import me.peng.domain.RecyclerFind;
import me.peng.domain.config.SysResult;
import me.peng.domain.mapper.CommentTowMapper;
import me.peng.domain.mapper.FindMapper;
import me.peng.utils.ValidationUtil;
import me.peng.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.peng.repository.CommentRepository;
import me.peng.service.CommentService;
import me.peng.service.dto.CommentDto;
import me.peng.service.dto.CommentQueryCriteria;
import me.peng.service.mapstruct.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.peng.utils.PageUtil;
import me.peng.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author pengjianye
* @date 2021-10-13
**/
@Service
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {

    private final CommentRepository commentRepository;
    private final CommentMapper commentMapper;
    @Autowired
    FindMapper findMapper;
    @Override
    public Map<String,Object> queryAll(CommentQueryCriteria criteria, Pageable pageable){
        Page<Comment> page = commentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(commentMapper::toDto));
    }

    @Override
    public List<CommentDto> queryAll(CommentQueryCriteria criteria){
        return commentMapper.toDto(commentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public CommentDto findById(Integer id) {
        Comment comment = commentRepository.findById(id).orElseGet(Comment::new);
        ValidationUtil.isNull(comment.getId(),"Comment","id",id);
        return commentMapper.toDto(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommentDto create(Comment resources) {
        return commentMapper.toDto(commentRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Comment resources) {

        Comment comment = commentRepository.findById(resources.getId()).orElseGet(Comment::new);
        ValidationUtil.isNull( comment.getId(),"Comment","id",resources.getId());
        comment.copy(resources);
        commentRepository.save(comment);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {

            //评论id
            Comment comment=commentMapper2.selectById(id);
            //根据评论id查询到它的findID再查询总的评论数值-1
            RecyclerFind recyclerFind=findMapper.selectById(comment.getFindid());
            int commentNumber=recyclerFind.getCommentnumber()-1;

            //再修改评论数
            putFindInfo(new RecyclerFind().setId(comment.getFindid()).setCommentnumber(commentNumber));
            commentRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<CommentDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CommentDto comment : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("动态ID", comment.getFindid());
            map.put("用户ID", comment.getParenid());
            map.put("用户名", comment.getName());
            map.put("评论内容", comment.getCmtcontent());
            map.put("点赞数", comment.getThumbsnum());
            map.put("评论时间", comment.getCretedata());
            map.put("评论信息", comment.getComentinfo());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Autowired
    CommentTowMapper commentMapper2;
    /**
     * 根据Findid查询
     * 查询评论
     * @return
     */
    @Override
    public SysResult getCommentInfo(Integer findId) {

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        //selec * from recycler_address where parent_id=findid
        queryWrapper.eq("findid", findId);
        List<Comment> list=commentMapper2.selectList(queryWrapper);

        return SysResult.success(list);
    }



    /**
     * 数据保存到数据库
     * @param postCommentInfo
     */
    @Override
    public SysResult postCommentInfo(Comment postCommentInfo) {

        /**
         * 每提交一条评论就将根据id查询的值的基础上加一
         * 根据findId 查询内容管理的评论数并在此基础上加一
         */
        RecyclerFind recyclerFind=findMapper.selectById(postCommentInfo.getFindid());
        int commentNumber=recyclerFind.getCommentnumber()+1;

        //修改评论数
        putFindInfo(new RecyclerFind().setId(postCommentInfo.getFindid()).setCommentnumber(commentNumber));
        //插入数据
        commentMapper2.insert(postCommentInfo);

        return SysResult.success();
    }


    //修改评论数
    public SysResult putFindInfo(RecyclerFind recyclerFind) {
        int update = findMapper.updateById(recyclerFind);
        return SysResult.success(update);
    }


}
